import {messages, trim} from "share/common";
import React from 'react';
import ReactDOM from 'react-dom';
import { Select, Icon, Popover, message } from 'antd'
import ListSelector from 'components/list-selector'
import 'styles/components/chooser.scss'
import expenseReportService from 'containers/expense-report/expense-report.service'

/**
 * 列表选择表单组件，由antd的select组件改造而来,select + listSelector的自定义表单组件
 *
 * 2018/11/26 ZaraNengap
 * 还有隐藏bug（大概
 * 但是到现在为止运行没问题，所以我就不想花时间在这个东西上面了
 * 这个组件在项目内大范围使用（非常大），所以如果要改请谨慎
 *
 */
class Chooser extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      value: [],
      showListSelector: false,
      listSelectedData: [],
    };
  }

  componentWillMount(){
   this.setValue(this.props.value);
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this)
      }
  }

  setValue = valueWillSet => {
    if(valueWillSet &&
      typeof valueWillSet !== 'string' && //onlyNeed模式下返回的single值
      !(valueWillSet.splice && valueWillSet.length > 0 && typeof valueWillSet[0] === 'string')  //onlyNeed模式下返回的只有需要值数组
    ){
      let lengthChange = valueWillSet.length !== this.state.value.length;
      let innerChange = false;
      if(valueWillSet.length === this.state.value.length){
        valueWillSet.map((nextItem, index) => {
          innerChange = innerChange || this.state.value[index].key !== (nextItem[this.props.valueKey] + '');
        })
      }
      if(lengthChange || innerChange){
        let values = [];
        valueWillSet.map(item => {
          values.push({
            key: item[this.props.valueKey] + '',
            label: item[this.props.labelKey],
            value: item
          });
        });
        this.setState({ value: values });
        !this.props.itemMap && this.onChange(valueWillSet);
      }
    }
    if((!valueWillSet && this.state.value.length > 0) || (valueWillSet && valueWillSet.length === 0 && this.state.value.length > 0)){
      this.setState({ value: [] });
    }
  };

  /**
   * value为传入值
   * @param nextProps
   */
  componentWillReceiveProps = nextProps => {
    // console.log('nextProps', nextProps)
    // 其他事项申请单报错了，因为nextProps.value值是object，导致setValue里面map方法报错了，暂时先在这改下
    if (nextProps.type !== 'auto_audit_add_company') {
      this.setValue(nextProps.value);
    }
  };

  /**
   * list控件因为select没有onClick事件，所以用onFocus代替
   * 每次focus后，用一个隐藏的input来取消聚焦
   */
  handleFocus = () => {
    this.refs.chooserBlur.focus();
    if (this.props.type === 'c5_people' || this.props.type === 'restaurant_people') {
      if (this.props.listExtraParams && this.props.listExtraParams.costCenterItemOId) {
        this.showList();
      } else {
        message.warning(messages('common.pleaseChooseCostCenter')/*请先选择成本中心*/)
      }
    } else {
      this.showList();
    }
  };

  handleMouseEnter = () => {
    let temp = ReactDOM.findDOMNode(this).getElementsByTagName('li');
    Array.from(temp).forEach(item => {
      item.removeAttribute('title');
    });
  };

  /**
   * 显示ListSelector，如果有已经选择的值则包装为ListSelector需要的默认值格式传入
   */
  showList = () => {
    let listSelectedData = [];
    if(this.state.value.length > 0){
      this.state.value.map(value => {
        listSelectedData.push(value.value);
      });
    }
    this.setState({ listSelectedData }, () => {
      this.setState({  showListSelector: true });
    })
  };

  handleListCancel = () => {
    this.setState({ showListSelector: false });
  };

  /**
   * ListSelector确认点击事件，返回的结果包装为form需要的格式
   * @param result
   */
  handleListOk = result => {
    let value = [];
    result.result.map(item => {
      value.push({
        key: item[this.props.valueKey],
        label: item[this.props.labelKey],
        value: item
      })
    });
    //手动调用onChange事件以与父级Form绑定
    this.onChange(result.result, 'handleListOk');
    this.setState({ showListSelector: false, value });
  };

  clear = () => {
    this.onChange([], 'clear');
    this.setState({ value: [] })
  };

  onChange = (changedValue, from) => {
    const { onlyNeed, onChange, single, type, labelKey } = this.props;
    if (onChange) {
      if(onlyNeed && changedValue){
        if(single)
          // onChange(changedValue[0] ? changedValue[0][onlyNeed] : []);
          // wjk 注释掉上一行，只需要某一个字段却不存在时应返回null
          if (type === 'third_user') {
            onChange(changedValue[0] ? trim(changedValue[0][labelKey]) + ',' + trim(changedValue[0][onlyNeed]) : null, changedValue[0], from);
          } else {
            onChange(changedValue[0] ? changedValue[0][onlyNeed] : null, changedValue[0], from);
          }
        else{
          let result = [];
          changedValue.map(item => {
            result.push(item[onlyNeed]);
          });
          //bugfix 41634 fieldsStore.getFieldMeta获取为空对象的问题
          try {
            onChange(result, null, from);
          } catch (e) {
            //console.log(e);
          }
        }
      }
      else{
        onChange(changedValue, null, from);
      }
    }
  };

  renderPopoverContent = (value) => {
    if (this.props.renderPopoverContent) {
      return this.props.renderPopoverContent(value)
    }
    return value.map(v => v.label).join("，")
  }

  renderValue = (value) => {
    if (this.props.renderValue) {
      return this.props.renderValue(value)
    }
    return value.map(v => v.label).join("，")
  }

  render() {
    const { showListSelector, listSelectedData, value } = this.state;
    const { placeholder, disabled, selectorItem, type, listExtraParams, single, noValueError,
      showNumber, size = 'middle', newline, maxNum, labelKey, showClear, showArrow, additionalDefault, showDetail, valueKey, hidePagination, popoverParams, reportId } = this.props;
    let popVisible = showNumber || !value.length ? {visible: false} : {};
    return (
      <div className={`chooser ${showNumber && 'number-only'} ${disabled && 'chooser-disabled'} ${newline && 'newline'}`}>
        <Popover
          placement="topLeft"
          content={this.renderPopoverContent(value)}
          {...popVisible}
          {...popoverParams}
        >
          <Select
            style={{ width: '100%' }}
            value={value}
            size={size}
            mode="multiple"
            labelInValue
            placeholder={placeholder}
            onMouseEnter={this.handleMouseEnter}
            onFocus={this.handleFocus}
            dropdownStyle={{ display: 'none' }}
            maxTagPlaceholder={<div>{value.map(v => v.label).join(",")}</div>}
            disabled={disabled}
          />
          {value.length && !newline ? (
            <div className={`fake-value-list ${disabled ? 'disabled' : ''}`} onClick={disabled ? () => {} : this.handleFocus}>
              {this.renderValue(value)}
            </div>) : ''
          }
        </Popover>
        {/*如果禁用了，就不要后面的清除icon*/}
        {
          (disabled || !showClear) ? "" : <Icon className="ant-select-selection__clear" type="close-circle" onClick={this.clear} style={value.length === 0 ? {opacity: 0} : {}}/>
        }
        <div className="chooser-number" onClick={() => { !this.props.disabled && this.showList() }}>
          {/*已选择 {value.length} 条*/}
          {messages("common.total.selected" , { total: value.length === 0 ? '0' : value.length })}
        </div>
        <ListSelector
          visible={showListSelector}
          type={type}
          onCancel={this.handleListCancel}
          onOk={this.handleListOk}
          selectedData={listSelectedData}
          extraParams={listExtraParams}
          selectorItem={selectorItem}
          single={single}
          maxNum={maxNum}
          labelKey={labelKey}
          valueKey={valueKey}
          hidePagination={hidePagination}
          showDetail={!single && showDetail}
          showArrow={showArrow}
          additionalDefault={additionalDefault}
          method={this.props.method}
          extraBottom ={this.props.extraBottom}
          modalRef={this.props.modalRef}
          noValueError={noValueError}
          reportId={reportId}
        />
        <div>
          <input
            ref="chooserBlur"
            style={{ opacity: 0, position: 'fixed', width: 0, height: 0, zIndex: -1 }}
          />
        </div>
      </div>
    );
  }
}

Chooser.propTypes = {
  onRef:React.PropTypes.func,
  placeholder: React.PropTypes.string,  //输入框空白时的显示文字
  disabled: React.PropTypes.bool,  //是否可用
  type: React.PropTypes.string,  //list选择的type，参见chooserData内
  selectorItem: React.PropTypes.object,  //listSelector的selectorItem
  valueKey: React.PropTypes.string,  //表单项的id变量名
  labelKey: React.PropTypes.string,  //表单项的显示变量名
  hidePagination: React.PropTypes.bool,  //表单项的key
  listExtraParams: React.PropTypes.object,  //listSelector的额外参数
  onChange: React.PropTypes.func,  //进行选择后的回调
  renderValue: React.PropTypes.func,  //
  renderPopoverContent: React.PropTypes.func,  //
  single: React.PropTypes.bool,  //是否单选
  value: React.PropTypes.oneOfType([React.PropTypes.array, React.PropTypes.string]),  //已选择的值，需要传入完整目标数组
  showNumber: React.PropTypes.bool,  //是否只显示'已选XX条'
  onlyNeed: React.PropTypes.any,  //只需要对象内的某一值的对应变量名
  newline: React.PropTypes.bool,  //内容是否可换行
  maxNum: React.PropTypes.number,  //最多选择多少条数据
  method: React.PropTypes.string,  //调用方法get/post
  showClear: React.PropTypes.bool, //是否显示clear
  showArrow: React.PropTypes.bool,  //是否在Tag中显示箭头
  additionalDefault: React.PropTypes.array, // 默认标签，在选项之外
  showDetail: React.PropTypes.bool,  //是否显示详情
  itemMap: React.PropTypes.bool,
  size: React.PropTypes.string,
  noValueError: React.PropTypes.string,  //没有值时的报错信息
  modalRef: React.PropTypes.func,   // 获取子组件方法
  popoverParams: React.PropTypes.object// popover相关参数
};

Chooser.defaultProps = {
  placeholder: messages("common.please.select"),
  disabled: false,
  listExtraParams: {},
  single: false,
  showNumber: false,
  newline: false,
  method: 'get',
  showClear: true,
  showArrow: false,
  size: 'middle',
  additionalDefault: [],
  showDetail: true,
  itemMap: false,
  popoverParams: {}
};

export default Chooser;
